//
//  KTMainViewController.m
//  BoWuGuan
//
//  Created by 梁尚嘉 on 2016/10/31.
//  Copyright © 2016年 KT. All rights reserved.
//

#import "MainViewController.h"

#import "BaseNavigationController.h"
#import "TabBarViewController.h"
#import "OMHomeAddressSelectViewController.h"

#import "MainConfigure.h"
#import "Storage.h"

#import "FLGuideView.h"


@interface MainViewController ()

@property (nonatomic, weak) UIViewController *currentVCtrl;
@property (nonatomic, assign) BOOL isTransitioning;
@property (nonatomic, weak) UIButton *badgeView;

@end

@implementation MainViewController


- (instancetype)init
{
    self = [super init];
    if (self) {
        [self configure];
    }
    return self;
}

- (void)configure
{
//    if (KTSystemStorageSingleton.originalAddress) {
//        //已选择地址,加载HomeVC
        _currentVCtrl = self.tabbarCtrl;
//
//    }else {
////        //未选择地址加载地址VC
//        _currentVCtrl = self.addressCtrl;
////
//    }
    [self.view addSubview:self.currentVCtrl.view];
    _cartButton = KTSystemStorageSingleton.cartButton;
    [_cartButton addTarget:self action:@selector(shopCartButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.cartButton];
    [self.cartButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(@(SM_SIZE(-5)));
        make.bottom.equalTo(@(SM_SIZE(-25)-49));
        make.width.height.equalTo(@(SM_SIZE(150)));
    }];
    _badgeView = KTSystemStorageSingleton.badgeView;
    [self setBadge:KTSystemStorageSingleton.numOfCartItem];

    [self observeSetup];

    FLGuideView *guide = [FLGuideView customGuideView];
    [guide showInView:self.view withComplection:^{}];
}

- (void)getCartNum
{
    NSString *cartKey = KTSystemStorageSingleton.cartKey;
    NSDictionary *parameters = !cartKey.length?nil:@{@"cartKey":KTSystemStorageSingleton.cartKey};
    [self.task cancel];
    self.task = [KTHttpUtils GET_NOCACHE:@"cart/count.jhtml"
                          parameters:parameters
                            progress:nil
                          completion:^(id responseObject, BOOL isSuccess, NSString *message) {
                              if (isSuccess) {
                                  KTSystemStorageSingleton.numOfCartItem = [responseObject[OMDatumKey] intValue];
                              }
    }];
}

- (void)observeSetup
{
    @weakify(self);
    [SMNotificationMonitorRACSignal(SM_NOTIFACATION_NEED_CARTITEM_SHOW) subscribeNext:^(id x) {
        @strongify(self);
        self.cartButton.hidden = NO;
        [self getCartNum];
    }];

    [SMNotificationMonitorRACSignal(SM_NOTIFACATION_NEED_CARTITEM_UPDATE) subscribeNext:^(id x) {
        @strongify(self);
        [self getCartNum];
    }];

    [SMNotificationMonitorRACSignal(SM_NOTIFACATION_NEED_CARTITEM_DISMISS) subscribeNext:^(id x) {
        @strongify(self);
        self.cartButton.hidden = YES;
    }];

    [SMNotificationMonitorRACSignal(KTOrginalAddressNotificationKey) subscribeNext:^(id x) {
        @strongify(self);
        if (self.currentVCtrl == self.addressCtrl) {
            [self transitionViewControllerWithAnimated:true];
        }
    }];

    //购物车数量
    [SMNotificationMonitorRACSignal(OMSHOPPINGCART_BADAGE_NUM_CHANGE_NOTIFICATION) subscribeNext:^(NSNotification *notification) {
        @strongify(self);
        [self setBadge:[notification.object unsignedIntegerValue]];
    }];
}



- (void)shopCartButtonClick:(UIButton *)button
{
    NaviPush(@"OMShoppingCartViewController", nil);
}

//MARK: GETTERS


- (void)viewWillLayoutSubviews
{
    
}

- (void)setBadge:(NSUInteger)number
{
    _badgeView.hidden = !number;
    [_badgeView setTitle:[@(number) stringValue] forState:UIControlStateNormal];
}

- (UIViewController *)currentViewController
{
    return _currentVCtrl;
}

- (void)transitionViewControllerWithAnimated:(BOOL)animated
{
    UIViewController *targetCtrl = nil;
    targetCtrl = _currentVCtrl == self.tabbarCtrl ? self.addressCtrl : self.tabbarCtrl;

    if (!targetCtrl || !_currentVCtrl || _isTransitioning)
    {
        return;
    }

    //登录与非登录取反，并保存
    _isTransitioning = YES;

    [self transitionFromViewController:_currentVCtrl
                      toViewController:targetCtrl
                              duration:animated ?.6f:0
                               options:UIViewAnimationOptionTransitionCrossDissolve
                            animations:nil
                            completion:^(BOOL finished) {

                                _isTransitioning = NO;
                                [_currentVCtrl removeFromParentViewController];
                                _currentVCtrl = targetCtrl;
                            }];
    
}


- (BaseNavigationController *)addressCtrl
{
    if (!_addressCtrl) {
        id controller = navigationCtrlMake([OMHomeAddressSelectViewController new]);
        [self addChildViewController:controller];
        _addressCtrl = controller;
    }
    return _addressCtrl;
}


- (TabBarViewController *)tabbarCtrl
{
    if (!_tabbarCtrl) {
        TabBarViewController *controller =  [TabBarViewController new];
        _tabbarCtrl = controller;
        [self addChildViewController:_tabbarCtrl];

    }
    return _tabbarCtrl;
}

- (void)cancelLoginAction
{
    CATransition* animation = [CATransition animation];
    [animation setDuration:0.2f];
    [animation setType:kCATransitionFade];
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
    [[self.view layer]addAnimation:animation forKey:@"switchView"];
    [self.tabbarCtrl setSelectedIndex:0];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
